package com.olc.railing.camera;


import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.olc.railing.base.BaseActivity;
import com.olc.railing.base.BaseApplication;
import com.tianyuxinghang.sxmobileterm.utils.MyLog;
import com.tianyuxinghang.sxmobileterm.utils.SPUtils;

import java.io.IOException;

public class CameraPreview extends FrameLayout {

    private static final String TAG = "CameraPreviewView";
    private static final float[] ASPECT_RATIO_ARRAY = {9.0f / 16, 3.0f / 4};
    public Camera mCamera;
    private CameraSurfaceView mSurfaceView;
    private PreviewCallback mPreviewCallback;
    public float mAspectRatio = ASPECT_RATIO_ARRAY[0];

    public int mWidth;
    public int mHeight;
    public SurfaceHolder mHolder;

    public interface PreviewCallback {
        void onPreviewStarted(Camera camera);
    }

    public CameraPreview(Context context) {
        super(context);
        init(context);
    }

    public void setPreviewCallback(PreviewCallback previewCallback) {
        mPreviewCallback = previewCallback;
    }

    public CameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        addView(context);
    }

    private void addView(Context context) {
        // 添加一个 View 占满屏幕，否则 mIvFocus 在屏幕下方显示时会被切掉一部分，原因未知
        addView(new View(context), new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        mSurfaceView = new CameraSurfaceView(context);
        addView(mSurfaceView, 0, new LayoutParams(LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 屏幕空间足够就显示 16:9，否则显示 4:3
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int maxHeight = MeasureSpec.getSize(heightMeasureSpec);
        int height = (int) (width / ASPECT_RATIO_ARRAY[0]);
        for (float ratio : ASPECT_RATIO_ARRAY) {
            height = (int) (width / ratio);
            if (height <= maxHeight) {
                mAspectRatio = ratio;
                break;
            }
        }
        int wms = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
        int hms = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(wms, hms);
    }

    private class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

        public CameraSurfaceView(Context context) {
            super(context);
            getHolder().addCallback(this);
        }

        public CameraSurfaceView(Context context, AttributeSet attrs) {
            super(context, attrs);
            getHolder().addCallback(this);
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {

        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            CameraPreview.this.mHolder = holder;
            CameraPreview.this.mWidth = width;
            CameraPreview.this.mHeight = height;
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.d(TAG,"surfaceDestroyed");
            releaseCamera();
        }

        @SuppressWarnings("SuspiciousNameCombination")
        private void openCameraVedio() {
            int mCameraId = (int) SPUtils.get(BaseApplication.getApplication(),"cameraId",0);
            MyLog.e(TAG,"openCamera mCameraId："+mCameraId);
            mCamera = CameraHelper.openCamera(mCameraId);
            MyLog.e(TAG,"openCamera mCamera："+mCamera);
        }

        @SuppressWarnings("SuspiciousNameCombination")
        private void openCamera(SurfaceHolder holder, int width, int height,int carmeraId) {

//            if (mCamera != null) { // 二维码扫描，当跳转界面后，必须要重新打开相机，否则不重新扫描
//                return;
//            }
           // int id = (int) SPUtils.get(BaseApplication.getApplication(),"cameraId",0);
            //int mCameraId = 0;
            MyLog.e(TAG,"openCamera id："+carmeraId);
            mCamera = CameraHelper.openCamera(carmeraId);
           // MyLog.e(TAG,"openCamera mCamera："+mCamera);
            if (mCamera == null) {
                return;
            }
            CameraHelper.setOptimalSize(mCamera, mAspectRatio, height, width);
            CameraHelper.setDisplayOritation((Activity) getContext(), mCamera, carmeraId);
            try {
                mCamera.setPreviewDisplay(holder);
                doStartPreview();
            } catch (IOException e) {
                MyLog.e(TAG, "startPreview open camera failed: " + e.getMessage());
                releaseCamera();
            }
        }

        private void doStartPreview() {
//            Log.e(TAG, "doStartPreview mPreviewCallback:" + mPreviewCallback);
            mCamera.startPreview();
            cameraFocus(CameraPreview.this.getWidth() / 2.0f, CameraPreview.this.getHeight() / 2.0f);
            if (mPreviewCallback != null) {
                mPreviewCallback.onPreviewStarted(mCamera);
            }
        }

        private void cameraFocus(final float x, final float y) {
            mCamera.cancelAutoFocus();
            CameraHelper.setFocusMode(mCamera, Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        }

        private void releaseCamera() {
            Log.d(TAG,"releaseCamera");
            if (mCamera != null) {
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }

    }

    /**
     * Camera start preview.
     */
    public boolean start(int carmeraId) {
        mSurfaceView.openCamera(mHolder, mWidth, mHeight,carmeraId);
        return true;
    }

    /**
     * Camera start preview.
     */
    public boolean startVdeio() {
        mSurfaceView.openCameraVedio();
        return true;
    }

    /**
     * Camera stop preview.
     */
    public void stop() {
        Log.d(TAG,"stop");
        mSurfaceView.surfaceDestroyed(mHolder);
    }

}
